//
//  EFengShareSelectDepController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/14.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengShareSelectDepController.h"

#import "EFengOrgnizationSelectionCell.h"

#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CXmppMgr.h"
#import "NSArray+PinYin.h"
#import "CXmppRequestMgr.h"
#import "CAccountModel.h"
#import "CFolderMgr.h"
#import "CServerSettingMgr.h"
#import "UIImage+ImageWithColor.h"
#import "IMSearchDisplayController.h"
#import "UIBarButtonItem+category.h"
#import "CPresenceModel.h"
#import "CPresenceMgr.h"
#import "EFengLatestContactSelectCell.h"
#import "UIImage+ImageWithColor.h"
#import "MBProgressHUD+WZ.h"
#import "CGroupModel.h"
#import "CHChatRoomBase.h"
#import "CGroupMemberMgr.h"
#import "CGroupMemberModel.h"
#import "CGroupMgr.h"

#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f

@interface EFengShareSelectDepController ()<UITableViewDelegate, UITableViewDataSource, EFengOrgnizationSelectionCellDelegate>

{
    UITableView *_tableView;
    NSString *_departId;
    NSArray *_departList;
    NSArray *_contactList;
    CContactMgr *_contactMgr;
    CDepartmentMgr *_departMentMgr;
    NSInteger _contactNum;
    CGroupMemberMgr *_groupMemMgr;
    
}
StrongProperty NSMutableArray *subDepArray;
StrongProperty NSMutableArray *subMemberArray;
WeakProperty UIButton *bottomButton;
StrongProperty NSArray *selectedArray;
StrongProperty CContactModel *curUser;
StrongProperty NSMutableArray *depAllmemArray;
StrongProperty NSMutableArray *unSelectdepAllmemArray;

@end





@implementation EFengShareSelectDepController

- (NSMutableArray *)unSelectdepAllmemArray
{
    if (_unSelectdepAllmemArray == nil) {
        _unSelectdepAllmemArray = [NSMutableArray array];
    }
    return _unSelectdepAllmemArray;
}
- (NSMutableArray *)depAllmemArray
{
    if (_depAllmemArray == nil) {
        _depAllmemArray = [NSMutableArray array];
    }
    return _depAllmemArray;
}


- (NSMutableArray *)subDepArray
{
    if (_subDepArray == nil) {
        _subDepArray = [NSMutableArray array];
    }
    return _subDepArray;
}

- (NSMutableArray *)subMemberArray
{
    if (_subMemberArray == nil) {
        _subMemberArray = [NSMutableArray array];
    }
    return _subMemberArray;
}
-(id)initWithDepartId:(NSString *)departId
{
    self = [super init];
    if(self)
    {
        _departId = departId;
    }
    return self;
}

- (void)dealloc
{
    
    //    NSLog(@"departDetailVC");
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    
    _departList = [_departMentMgr loadDepartments:_departId];
    
    [_departList enumerateObjectsUsingBlock:^(CDepartmentModel *obj, NSUInteger idx, BOOL * stop) {
        [self.depAllmemArray removeAllObjects];
        [self.unSelectdepAllmemArray removeAllObjects];
        _contactNum = 0;
        [self loadAllSubDepMemWithDepId:obj.DEPTID];
        [self loadAllSelectedMemCountWithDepId:obj.DEPTID];
        [self.unSelectdepAllmemArray addObjectsFromArray:self.depAllmemArray];
        
        for (CContactModel *obj in self.depAllmemArray) {
            if ([obj.UserID isEqualToString:self.curUser.UserID]) {
                [self.unSelectdepAllmemArray removeObject:obj];
            }
        }
        obj.UserNum = self.unSelectdepAllmemArray.count;
        if (obj.UserNum <= _contactNum && obj.UserNum > 0) {
            obj.isSelected = YES;
        } else {
            obj.isSelected = NO;
        }
    }];
    
    [_tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(backForPop) titleFont:Font18 titleColor:WhiteColor];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    _contactNum = 0;
    _departMentMgr = [[CDepartmentMgr alloc] init];
    CServerSettingModel *setting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    _departMentModel = [_departMentMgr loadDepartment:_departId];
    _contactMgr = [[CContactMgr alloc] init];
    //    _departList = [_departMentMgr loadDepartments:_departId];
    //    _contactList = [NSArray sortArray:[_contactMgr loadContactByDeptID:_departId]];
       _groupMemMgr = [[CGroupMemberMgr alloc] init];
    
    if (_departMentModel == nil) {
        [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
    } else {
        if (_departMentModel.DepartName.length > 0) {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",_departMentModel.DepartName]];
        } else {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
        }
        
    }
    
    
    //加载我的父部门信息
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curUser = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f) style:UITableViewStyleGrouped];
    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    _tableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
}



- (void)createDiscussList
{
    
}

- (void)backForPop
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
        NSInteger rows = 0;
        switch (section) {
            case 0:
                if([_departList count] > 0)
                {
                    rows = [_departList count];
                }
                else
                {
                    rows = [_contactList count];
                }
                break;
            case 1:
                rows = [_contactList count];
                break;
            default:
                rows = 0;
                break;
        }
        return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
        NSInteger section = 0;
        if([_departList count] > 0)
        {
            section ++;
        }
        if([_contactList count] > 0)
        {
            section ++;
        }
        
        return section;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITableViewCell *cell = nil;
        EFengOrgnizationSelectionCell *departCell = [EFengOrgnizationSelectionCell eFengOrgnizationSelectionCellWithTableView:tableView];
        departCell.orgnizationDelegate = self;
        departCell.cellIndexPath = indexPath;
        departCell.tableView = tableView;
            
        [departCell.departIcon  setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
        CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
        [departCell.departNameLabel setText:departModel.DepartName];
            
            
            //  bug 6106 fixed by 荣则兵
        [departCell.departCountLabel setText:@""];
            
            //            if (departModel.UserNum > 0) {
            //
            //                [departCell.departCountLabel setText:[NSString stringWithFormat:@"%zd", departModel.UserNum]];
            //
            //            } else {
            //            }
            
            
            if(indexPath.section == 0 && indexPath.row == _departList.count - 1)
            {
                [departCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departCell.seperatorLine setHidden:NO];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departCell;
            
            departCell.selectIcon.selected = departModel.isSelected;
    return departCell;
}




#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0.01f;
    //    switch (section) {
    //        case 1:
    //            height = 2;
    //            break;
    //        default:
    //            break;
    //    }
    return height;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    return count;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    //    if(section != 1 && [_contactList count] > 0)
    //    {
    //        return headerView;
    //    }
    //    if(section == 0 && [_departList count] > 0)
    //    {
    //        return headerView;
    //    }
    //
    //    headerView = [[UIView alloc] init];
    //    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    //    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    //    UIView *beginLine = [[UIView alloc] init];
    //    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    //    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    //    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_tableView == tableView) {
        
        switch (indexPath.section) {
            case 0:
            {
                if (_departList.count > 0) {
                    CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
                    [self showDepartDetailVC:departModel.DEPTID];
                } else {
                    
                }
            }
                break;
                
                
            case 1:
            {
                
            }
                break;
                
            default:
                break;
        }
    } else {
        
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return NO;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"删除";
}




-(void)showDepartDetailVC:(NSString *)currentDepartId
{
    EFengShareSelectDepController *departDetail = [[EFengShareSelectDepController alloc] initWithDepartId:currentDepartId];
    [self.navigationController pushViewController:departDetail animated:YES];
    
}


#pragma mark cellde 代理方法

- (void)EFengOrgnizationSelectionCellDidSelectWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    
    
    __block CDepartmentModel *dep = _departList[indexPath.row];
    
    dep.isSelected = !dep.isSelected;
    [self.subMemberArray removeAllObjects];
    [self.subDepArray removeAllObjects];
    [self.unSelectdepAllmemArray removeAllObjects];
    [self loadAllSubdDepAndMemberWithDep:dep];
    [self.unSelectdepAllmemArray addObjectsFromArray:self.subMemberArray];
    
    for (CContactModel *obj in self.subMemberArray) {
        if ([obj.UserID isEqualToString:self.curUser.UserID]) {
            [self.unSelectdepAllmemArray removeObject:obj];
        }
    }
    
    
    
    [_contactMgr updateSelectWithContactList:self.unSelectdepAllmemArray isSelected:dep.isSelected];
    [_departMentMgr updateSelectWithDeptList:self.subDepArray isSelected:dep.isSelected];
    
    [_departMentMgr updateDeptSelectedWithDept:dep seleceted:dep.isSelected];
    [_tableView reloadData];
    
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    
}

- (void)loadAllSubdDepAndMemberWithDep:(CDepartmentModel *)dep
{
    NSArray *depArray = [_departMentMgr loadDepartments:dep.DEPTID];
    [self.subDepArray addObjectsFromArray:depArray];
    NSArray *contactArray = [_contactMgr loadContactByDeptID:dep.DEPTID];
    [self.subMemberArray addObjectsFromArray:contactArray];
    
    for (CDepartmentModel *dep in depArray) {
        [self loadAllSubdDepAndMemberWithDep:dep];
    }
}

- (void)loadAllSubDepMemWithDepId:(NSString *)depId
{
    
    NSArray *array = [_contactMgr loadContactUserIdAndDepIdByDeptID:depId];
    [self.depAllmemArray addObjectsFromArray:array];
    NSArray *depArray = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in depArray) {
        [self loadAllSubDepMemWithDepId:depModel.DEPTID];
    }
}

- (NSInteger)loadAllSelectedMemCountWithDepId:(NSString *)depId
{
    _contactNum = _contactNum + [_contactMgr loadAllSelectedCountContactWithDepId:depId];
    NSArray *array = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in array) {
        [self loadAllSelectedMemCountWithDepId:depModel.DEPTID];
    }
    return _contactNum;
    
}


@end
